/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication.storage.android.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Android-specific SQLite database helper implementation.
 */
public class SQLiteDatabaseHelper extends SQLiteOpenHelper {
	private static final String TAG = "SQLiteDatabaseHelper";

	private static final String DATABASE_NAME = "replication.db";
	private static final int DATABASE_VERSION = 10;

	/**
	 * Constructor.
	 * 
	 * @param context the context of the application.
	 * @see SQLiteOpenHelper#SQLiteOpenHelper(Context, String, android.database.sqlite.SQLiteDatabase.CursorFactory,
	 *      int)
	 */
	public SQLiteDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(TAG, "Creating database version " + DATABASE_VERSION);

		db.execSQL("CREATE TABLE subset ("
				+ "id INTEGER PRIMARY KEY ASC AUTOINCREMENT"
				+ ");");

		db.execSQL("CREATE TABLE knowledge ("
					+ "subset_id INTEGER REFERENCES subset (id) ON UPDATE CASCADE ON DELETE CASCADE, "
					+ "replica TEXT, "
					+ "version INTEGER, "
					+ "PRIMARY KEY (subset_id, replica) ON CONFLICT REPLACE"
				+ ");");

		db.execSQL("CREATE TABLE metadata ("
					+ "name TEXT PRIMARY KEY ON CONFLICT REPLACE, "
					+ "subset_id INTEGER REFERENCES subset (id) ON UPDATE CASCADE ON DELETE RESTRICT, "
					+ "replica TEXT, "
					+ "version INTEGER, "
					+ "timestamp INTEGER"
				+ ");");
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		// Enforce foreign key constraints.
		db.execSQL("PRAGMA foreign_keys = ON;");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i(TAG, "Upgrading database version from " + oldVersion + " to " + newVersion);

		db.execSQL("DROP TABLE IF EXISTS subset;");
		db.execSQL("DROP TABLE IF EXISTS knowledge;");
		db.execSQL("DROP TABLE IF EXISTS metadata;");

		onCreate(db);
	}
}